﻿package util ;


/**
 * ADAMS Engine Core. 
 * Copyright ⓒ 2010 LGHitachi Co., Ltd. All Rights Reserved.
 * 
 * @Program Name : DateTime.java
 * @Description :
 * 
 * @author Jun
 * @version 1.1 2010. 2. 18. Renewal 작업
 */

import java.text.ParseException;
import java.text.SimpleDateFormat ;
import java.util.Calendar ;
import java.util.Formatter;
import java.util.Locale ;
import java.util.Date ;
import java.util.SimpleTimeZone ;
import java.util.TimeZone ;


public final class DateTime {

    /**
     * Don't let anyone instantiate this class
     */

    private static final long _ONE_DAY_TIME_MIL_SEC = 1000*60*60*24;
    private static final String yyyyMMdd = "yyyyMMdd";
    private static final String yyyy_MM_dd = "yyyy-MM-dd";
    private DateTime () {}


    //날짜 형태 확인하기
    /**
     * 일자를 사용자가 정의한 형식에 의해 체크한다
     * @param s 체크하고자하는 date String
     * @param format 체크하고자 하는 형식 (예 : "yyyy-MM-dd")
     * @return boolean true 날짜 형식이 맞고, 존재하는 날짜일 때
     *                 false 날짜 형식이 맞지 않거나, 존재하지 않는 날짜일 때
     */
    public static boolean isValidDate ( String s, String format ) {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            format, java.util.Locale.KOREA ) ;
        java.util.Date date = null ;
        try {
            date = formatter.parse ( s ) ;
        } catch ( java.text.ParseException e ) {
            return false ;
        }

        if ( !formatter.format ( date ).equals ( s ) ) {
            return false ;
        }

        return true ;
    }


    /**
     * 현재(한국기준) 시간정보를 얻는다.                     <BR>
     * (예) 입력파리미터인 format string에 "yyyyMMddhh"를 셋팅하면 1998121011과 같이 Return.  <BR>
     * (예) format string에 "yyyyMMddHHmmss"를 셋팅하면 19990114232121과 같이
     *      0~23시간 타입으로 Return. <BR>
     *      String CurrentDate = ComUtil.getCurrentTime("yyyyMMddHH");<BR>
     * @param    format		얻고자하는 현재시간의 Type
     * @return   String 		현재 한국 시간.
     */
    public static String getCurrentTime ( String format ) {
    	return getFormatString(format, System.currentTimeMillis ());
    }


    /**
     * 현재(한국기준) 날짜정보를 얻는다.                     <BR>
     * @param   N/A
     * @return  String 		yyyymmdd형태의 현재 한국시간. 	<BR>
     */
    public static String getCurrentDate () {
        return getCurrentDate ( "" ) ;
    }


    /**
     * 현재(한국기준) 날짜정보를 얻는다.                     <BR>
     * (예) 입력파리미터인 format string에 "yyyy/MM/dd"를 셋팅하면 1998/12/10/과 같이 Return.  <BR>
     *      String CurrentDate = ComUtil.getCurrentDate("/");<BR>
     * @param   format		얻고자하는 현재시간의 Type
     * @return  String 		yyyy/mm/dd형태의 현재 한국시간. 	<BR>
     */
    public static String getCurrentDate ( String format ) {

        SimpleDateFormat fmt = new SimpleDateFormat ( "yyyy" + format + "MM" +
            format + "dd" ) ;

        Calendar aCalendar = Calendar.getInstance () ;
        String str = fmt.format ( aCalendar.getTime () ) ;
        return str ;
    }
    /**
     * 
     * @param format
     * @return
     */
    public static String getCurrentForamtDate (String format) {
        SimpleDateFormat fmt = new SimpleDateFormat (format) ;
        Calendar aCalendar = Calendar.getInstance () ;
        String str = fmt.format ( aCalendar.getTime () ) ;
        return str ;
    }
    

    /**
     * @return formatted string representation of current day with  "yyyy-MM-dd".
     */
    public static String getDateString () {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            "yyyy-MM-dd", java.util.Locale.KOREA ) ;
        return formatter.format ( new java.util.Date () ) ;
    }


    /**
     *
     * For example, String time = DateTime.getFormatString("yyyy-MM-dd HH:mm:ss");
     *
     * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
     * @return formatted string representation of current day and time with  your pattern.
     */
    public static int getDay () {
        return getNumberByPattern ( "dd" ) ;
    }
    public static int getDay(Date date) {
    	return getNumberByPattern("dd", date);
    }
    public static int getDay(long millisecond) {
    	return getNumberByPattern("dd", new Date(millisecond));
    }


    /**
     *
     * For example, String time = DateTime.getFormatString("yyyy-MM-dd HH:mm:ss");
     *
     * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
     * @return formatted string representation of current day and time with  your pattern.
     */
    public static String getFormatString ( String pattern ) {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            pattern, java.util.Locale.KOREA ) ;
        String dateString = formatter.format ( new java.util.Date () ) ;
        return dateString ;
    }    
    public static String getFormatString ( String format, long datetime ) {
        //1hour(ms) = 60s * 60m * 1000ms
        int millisPerHour = 60 * 60 * 1000 ;
        SimpleDateFormat fmt = new SimpleDateFormat ( format ) ;

        SimpleTimeZone timeZone = new SimpleTimeZone ( 9 * millisPerHour, "KST" ) ;
        fmt.setTimeZone ( timeZone ) ;

        String str = fmt.format ( new java.util.Date ( datetime ) ) ;

        return str ;
    }


    /**
     *
     * For example, String time = DateTime.getFormatString("yyyy-MM-dd HH:mm:ss");
     *
     * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
     * @return formatted string representation of current day and time with  your pattern.
     */
    public static int getMonth () {
        return getNumberByPattern ( "MM" ) ;
    }
    public static int getMonth(Date date) {
    	return getNumberByPattern("MM", date);
    }
    public static int getMonth(long millisecond) {
    	return getNumberByPattern("MM", new Date(millisecond));
    }


    /**
     *
     * For example, String time = DateTime.getFormatString("yyyy-MM-dd HH:mm:ss");
     *
     * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
     * @return formatted string representation of current day and time with  your pattern.
     */
    public static int getNumberByPattern ( String pattern ) {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            pattern, java.util.Locale.KOREA ) ;
        String dateString = formatter.format ( new java.util.Date () ) ;
        return Integer.parseInt ( dateString ) ;
    }
    
    public static int getNumberByPattern(String pattern, Date date) {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
                pattern, java.util.Locale.KOREA ) ;
            String dateString = formatter.format ( date ) ;
            return Integer.parseInt ( dateString ) ;    	
    }


    /**
     * @return formatted string representation of current day with  "yyyyMMdd".
     */
    public static String getShortDateString () {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            "yyyyMMdd", java.util.Locale.KOREA ) ;
        return formatter.format ( new java.util.Date () ) ;
    }


    /**
     * @return formatted string representation of current time with  "HHmmss".
     */
    public static String getShortTimeString () {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            "HHmmss", java.util.Locale.KOREA ) ;
        return formatter.format ( new java.util.Date () ) ;
    }

    public static String addDate (String date, int addDay) {
        Calendar c = Calendar.getInstance();
        if(date != null && date.length() > 7) {
            if(date.length() == 8) {
                c.set(Util.stoi(date.substring(0, 4)),
                Util.stoi(date.substring(4,6))-1,
                Util.stoi(date.substring(6)));
                SimpleDateFormat formatter = new SimpleDateFormat (yyyyMMdd, Locale.KOREA ) ;
                c.setTimeInMillis(c.getTimeInMillis() + (_ONE_DAY_TIME_MIL_SEC*addDay)) ;
                return formatter.format (c.getTime() ) ;
            } else if(date.length() == 10) {
                c.set(Util.stoi(date.substring(0, 4)),
                Util.stoi(date.substring(5,7))-1,
                Util.stoi(date.substring(8)));
                SimpleDateFormat formatter = new SimpleDateFormat (yyyy_MM_dd, Locale.KOREA ) ;
                c.setTimeInMillis(c.getTimeInMillis() + (_ONE_DAY_TIME_MIL_SEC*addDay)) ;
                return formatter.format (c.getTime() ) ;
            } else {
                return "" ;
            }
        } else {
            return "" ;
        }

    }

/**
     * @return formatted string representation of current time with  "yyyy-MM-dd-HH:mm:ss".
     */
    public static String getTimeStampString () {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            "yyyy-MM-dd-HH:mm:ss:SSS", java.util.Locale.KOREA ) ;
        return formatter.format ( new java.util.Date () ) ;
    }


    /**
     * @return formatted string representation of current time with  "HH:mm:ss".
     */
    public static String getTimeString () {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (
            "HH:mm:ss", java.util.Locale.KOREA ) ;
        return formatter.format ( new java.util.Date () ) ;
    }


    /**
     *
     * For example, String time = DateTime.getFormatString("yyyy-MM-dd HH:mm:ss");
     *
     * @param java.lang.String pattern  "yyyy, MM, dd, HH, mm, ss and more"
     * @return formatted string representation of current day and time with  your pattern.
     */
    public static int getYear () {
        return getNumberByPattern ( "yyyy" ) ;
    }
    public static int getYear(Date date) {
    	return getNumberByPattern("yyyy", date);
    }
    public static int getYear(long millisecond) {
    	return getNumberByPattern("yyyy", new Date(millisecond));
    }
    

    /**
     *
     * @param s   date string you want to check.
     * @param format string representation of the date format. For example, "yyyy-MM-dd".
     * @return  date Date
     * @throws ParseException error info
     */
    public static long getDateTime(String s, String format) {
        try {
            //SimpleDateFormat formatter =  new SimpleDateFormat(format, Locale.KOREA);
        	SimpleDateFormat formatter = new SimpleDateFormat(format);
			return formatter.parse(s).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		return 0;
    }
    public static long getDateTime(int year, int month, int day, int hour, int min, int sec, int millisec) {
    	String sb = String.format("%d %d %d %d %d %d %d", year, month, day, hour, min, sec, millisec);
    	return getDateTime(sb, "yyyy MM dd HH mm ss SSS");
    }

    /**
     * from 포맷으로 정의된 날짜를 to 포맷으로 변경하여 반환한다.
     * @param datetime
     * @param from
     * @param to
     * @return
     */
    public static String convertFormatDateTime(String s, String from, String to) {
    	return getFormatString(to, getDateTime(s, from));
    }    
    
    
    public static String convertDateType ( String s , int length) {
        if ( s.length () == 0 || s == null ) {
            return "" ;
        }
        if(length == 10) {
            if(s.length() == 10) {
                StringBuffer sb = new StringBuffer() ;
                sb.append(s.substring(0, 4)).append("/")
                        .append(s.substring(5, 7)).append("/")
                        .append(s.substring(8, 10)) ;
                return sb.toString() ;
            } else if(s.length() == 8) {
                StringBuffer sb = new StringBuffer() ;
                sb.append(s.substring(0, 4))
                        .append(s.substring(5, 7))
                        .append(s.substring(8)) ;
                return sb.toString() ;
            } else {
                return "invalid length" ;
            }
        } else if(length == 8) {
            if(s.length() == 10) {
                StringBuffer sb = new StringBuffer() ;
                sb.append(s.substring(0, 4))
                        .append(s.substring(5, 7))
                        .append(s.substring(8, 10)) ;
                return sb.toString() ;
            } else if(s.length() == 8) {
                return s ;
            } else {
                return "invalid length" ;
            }
        } else {
            return "invalid length" ;
        }
    }


    public static String convertDateType2 ( String s ) {
        if ( s == null || s.length () == 0 ) {
            return "" ;
        }
        if ( s.length () < 8 ) {
            return "invalid length" ;
        }
        String s1 = s.substring ( 0, 4 ) ;
        String s2 = s.substring ( 4, 6 ) ;
        String s3 = s.substring ( 6, 8 ) ;
        StringBuffer stringbuffer = new StringBuffer () ;
        switch ( Integer.parseInt ( s2 ) ) {
            case 1: /* '\001' */
                stringbuffer.append ( "January" ) ;
                break ;

            case 2: /* '\002' */
                stringbuffer.append ( "February" ) ;
                break ;

            case 3: /* '\003' */
                stringbuffer.append ( "March" ) ;
                break ;

            case 4: /* '\004' */
                stringbuffer.append ( "April" ) ;
                break ;

            case 5: /* '\005' */
                stringbuffer.append ( "May" ) ;
                break ;

            case 6: /* '\006' */
                stringbuffer.append ( "June" ) ;
                break ;

            case 7: /* '\007' */
                stringbuffer.append ( "July" ) ;
                break ;

            case 8: /* '\b' */
                stringbuffer.append ( "August" ) ;
                break ;

            case 9: /* '\t' */
                stringbuffer.append ( "September" ) ;
                break ;

            case 10: /* '\n' */
                stringbuffer.append ( "October" ) ;
                break ;

            case 11: /* '\013' */
                stringbuffer.append ( "November" ) ;
                break ;

            case 12: /* '\f' */
                stringbuffer.append ( "December" ) ;
                break ;

            default:
                stringbuffer.append ( "None" ) ;
                break ;

        }
        stringbuffer.append ( " " ).append ( s3 ).append ( ", " ).append ( s1 ) ;
        return stringbuffer.toString () ;
    }


    public static String getDatewithSpan ( long l ) {
        int i = 0x36ee80 ;
        SimpleDateFormat simpledateformat = new SimpleDateFormat ( "yyyy-MM-dd" ) ;
        SimpleTimeZone simpletimezone = new SimpleTimeZone ( 9 * i, "KST" ) ;
        simpledateformat.setTimeZone ( simpletimezone ) ;
        long l1 = System.currentTimeMillis () ;
        long l2 = ( 24 * i ) * l ;
        long l3 = l1 + l2 ;
        return simpledateformat.format ( new Date ( l3 ) ) ;
    }


    public static String getDatewithSpan ( String s, long l ) {
        int i = 0x36ee80 ;
        SimpleDateFormat simpledateformat = new SimpleDateFormat ( "yyyy-MM-dd" ) ;
        SimpleTimeZone simpletimezone = new SimpleTimeZone ( 9 * i, "KST" ) ;
        simpledateformat.setTimeZone ( simpletimezone ) ;
        int j = Integer.valueOf ( s.substring ( 0, 4 ) ).intValue () ;
        int k = Integer.valueOf ( s.substring ( 4, 6 ) ).intValue () ;
        int i1 = Integer.valueOf ( s.substring ( 6, 8 ) ).intValue () ;
        Calendar calendar = Calendar.getInstance () ;
        Calendar calendar1 = Calendar.getInstance () ;
        calendar.set ( j, k, i1 ) ;
        calendar1.set ( 1970, 1, 1 ) ;
        calendar.add ( 2, -1 ) ;
        calendar1.add ( 2, -1 ) ;
        Date date = calendar.getTime () ;
        Date date1 = calendar1.getTime () ;
        Date date2 = new Date ( ( date.getTime () - date1.getTime () ) +
                                l * ( 24 * i ) ) ;
        return simpledateformat.format ( date2 ) ;
    }


    public static String getGMTDate () {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(
                            "GMT+00:00")) ;
        StringBuffer sb = new StringBuffer() ;
        sb.append(calendar.get(1)).append(Util.makeTowDigit(calendar.get(2) + 1))
        .append(Util.makeTowDigit(calendar.get(5)));
        return sb.toString() ;
    }


    public static String getGMTDateTime () {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(
                            "GMT+00:00")) ;
        StringBuffer sb = new StringBuffer() ;
        sb.append(calendar.get(1))
        .append(Util.makeTowDigit(calendar.get(2) + 1))
        .append(Util.makeTowDigit(calendar.get(5)))
        .append(Util.makeTowDigit(calendar.get(11)))
        .append(Util.makeTowDigit(calendar.get(12)))
        .append(Util.makeTowDigit(calendar.get(13)));
        return sb.toString() ;
    }


    public static String getLocalDate () {
        Calendar calendar = Calendar.getInstance () ;
        StringBuffer sb = new StringBuffer() ;
        sb.append(calendar.get ( 1 ))
        .append(Util.makeTowDigit ( calendar.get ( 2 ) + 1 ))
        .append(Util.makeTowDigit ( calendar.get ( 5 ) ));
        return sb.toString() ;
    }


    public static String getLocalDateTime () {
        Calendar calendar = Calendar.getInstance () ;
        StringBuffer sb = new StringBuffer() ;
        sb.append(calendar.get ( 1 ))
        .append(Util.makeTowDigit ( calendar.get ( 2 ) + 1 ))
        .append(Util.makeTowDigit ( calendar.get ( 5 ) ))
        .append(Util.makeTowDigit ( calendar.get ( 11 ) ))
        .append(Util.makeTowDigit ( calendar.get ( 12 ) ))
        .append(Util.makeTowDigit ( calendar.get ( 13 ) ));

        return sb.toString() ;
    }


    public static String getLocalDateTime ( String s ) {
        SimpleDateFormat simpledateformat = new SimpleDateFormat ( s ) ;
        long l = System.currentTimeMillis () ;
        String s1 = simpledateformat.format ( new Date ( l ) ) ;
        return s1 ;
    }


    public static String makeDateTimeType ( String s ) {
        if ( s.length () == 0 ) {
            return "" ;
        }
        if ( s.length () != 14 ) {
            return "invalid length" ;
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append(s.substring ( 0, 4 )).append("/")
            .append(s.substring ( 4, 6 )).append("/")
            .append(s.substring ( 6, 8 )).append(" ")
            .append(s.substring ( 8, 10 )).append(":")
            .append(s.substring ( 10, 12 )).append(":")
            .append(s.substring ( 12, 14 ));
            return sb.toString() ;
        }
    }


    public static String makeDateType ( String s ) {
        if ( s.length () == 0 || s == null ) {
            return "" ;
        }
        if ( s.length () != 8 ) {
            return "invalid length" ;
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append(s.substring ( 0, 4 )).append("/")
            .append(s.substring ( 4, 6 )).append("/")
            .append(s.substring ( 6, 8 )) ;
            return sb.toString();
        }
    }


    public static String makeTimeType ( String s ) {
        if ( s.length () == 0 || s == null ) {
            return "" ;
        }
        if ( s.length () != 6 ) {
            return "invalid length" ;
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append(s.substring ( 0, 2 )).append(":")
            .append(s.substring ( 2, 4 )).append(":")
            .append(s.substring ( 4, 6 ));
            return sb.toString() ;
        }

    }



    public static String getWeekDay ( String year, String month, String day ) {
        Calendar cal = Calendar.getInstance () ;

        cal.set ( cal.YEAR, Integer.parseInt ( year ) ) ;
        cal.set ( cal.MONTH, Integer.parseInt ( month ) - 1 ) ;
        cal.set ( cal.DATE, Integer.parseInt ( day ) ) ;

        String str = "" + cal.get ( cal.DAY_OF_WEEK ) ;

        str = "1".equals ( str ) ? "일"
              : "2".equals ( str ) ? "월"
              : "3".equals ( str ) ? "화"
              : "4".equals ( str ) ? "수"
              : "5".equals ( str ) ? "목"
              : "6".equals ( str ) ? "금"
              : "7".equals ( str ) ? "토" : "" ;

        return str ;

    }

    public static int getCalTermDay( String s_date, String e_date) {
         long term = -1;

        if(s_date != null && e_date !=  null &&
           s_date.length() == 10 && e_date.length() == 10 &&
           !"0001-01-01".equals(s_date) && !"0001".equals(e_date)) {
            Calendar cal = Calendar.getInstance();
            cal.set(Util.stoi(s_date.substring(0, 4)),
                    Util.stoi(s_date.substring(5, 7))-1,
                    Util.stoi(s_date.substring(8))
                    );
            Date s_d = cal.getTime();
            cal.set(Util.stoi(e_date.substring(0, 4)),
                    Util.stoi(e_date.substring(5, 7))-1,
                    Util.stoi(e_date.substring(8))
                    );
            Date e_d = cal.getTime();
            term = (e_d.getTime() - s_d.getTime())/_ONE_DAY_TIME_MIL_SEC;
          //  s_dt =
      } else if(s_date != null && e_date !=  null &&
         s_date.length() == 8 && e_date.length() == 8 ) {
          Calendar cal = Calendar.getInstance();

          cal.set(Util.stoi(s_date.substring(0, 4)),
                  Util.stoi(s_date.substring(4, 6))-1,
                  Util.stoi(s_date.substring(6))
                  );
          Date s_d = cal.getTime();
          cal.set(Util.stoi(e_date.substring(0, 4)),
                  Util.stoi(e_date.substring(4, 6))-1,
                  Util.stoi(e_date.substring(6))
                  );
          Date e_d = cal.getTime();
          term = (e_d.getTime() - s_d.getTime())/_ONE_DAY_TIME_MIL_SEC;
        //  s_dt =
      }


        return (int)term;
    }
    
    
    
    /**
     * format
     * 		"min hour day month week"
     * 	ex)	"10 * * * "
     * @param format
     * @return
     */
    public String getNearTime(String schedule, String format) {
    	String[] zone = schedule.split("[ ]");
    	
    	String[] minus = spliteSchedule(zone[0], "mm");	//	yyyyMMddHHmmss
    	String[] hours = spliteSchedule(zone[1], "HH");
    	String[] days = spliteSchedule(zone[2], "dd");
    	String[] months = spliteSchedule(zone[3], "MM");
    	
    	return null;
    }
    
    public String[] spliteSchedule(String onePart, String format) {
    	String[] data = null;
    	String[] ret = null;
    	if (onePart.matches("^\\d[-]\\d$"))	{	//	0-1
    		data = onePart.split("[-]");
    		int start = Integer.parseInt(data[0]);
    		int end = Integer.parseInt(data[1]);
    		ret = new String[end - start + 1];
    		for (int i = start; i <= end; i ++)
    			ret[i] = new String("" + i);    		
    	}
    	else if (onePart.matches("^(\\d[,]\\d)+$")) {			//	1,2,3,4
    		ret = onePart.split("[,]");
    	}
    	else if (onePart.matches("^\\d$")) {
    		ret = new String[1];
    		ret[0] = onePart;
    	}
    	else if (onePart.equals("*")) {
    		ret = new String[1];
    		ret[0] = getCurrentDate(format);
    	}
    	return ret;
    }
    
    
    
    
}
